package com.juyu.miliao.api.service;

import com.juyu.miliao.api.config.SegmentedLockManager;
import com.juyu.miliao.api.constant.GameNoobMissionConstant;
import com.juyu.miliao.api.dao.mysql.BillDetailBeansDao;
import com.juyu.miliao.api.dao.mysql.GameNoobMissionDao;
import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.dao.mysql.UserWalletDao;
import com.juyu.miliao.api.domain.GameNoobMission;
import com.juyu.miliao.api.domain.UserWallet;
import com.juyu.miliao.api.domain.dto.GameNoobMissionDTO;
import com.juyu.miliao.api.domain.dto.GameNoobMissionMqDTO;
import com.juyu.miliao.common.constant.BeansType;
import com.juyu.miliao.common.domain.BillDetailBeans;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.util.CheckSqlResultUtil;
import com.juyu.miliao.common.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.concurrent.locks.Lock;

import static com.juyu.miliao.api.constant.GameNoobMissionConstant.*;

/**
 * 游戏大厅,新手任务
 *
 * @author jh
 * @date 2019/09/16
 */
@Service
@Slf4j
public class GameNoobMissionService {

    @Resource
    private GameNoobMissionDao gameNoobMissionDao;
    @Resource
    private SegmentedLockManager segmentedLockManager;
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private UserWalletDao userWalletDao;
    @Resource
    private BillDetailBeansDao billDetailBeansDao;
    @Resource
    private GameDataService gameDataService;

    @RabbitListener(bindings = @QueueBinding(value = @Queue("GAME_NOOB_MISSION_QUEUE"),
            exchange = @Exchange(name = "GAME_NOOB_MISSION_EXCHANGE", type = "direct")))
    @RabbitHandler
    public void receive(GameNoobMissionMqDTO dto) {
        if (dto == null || dto.getType() == null || dto.getUserId() == null) {
            log.error("receiveMQ:GameNoobMissionMqDTO={}", dto);
            return;
        }

        GameNoobMission gameNoobMission = new GameNoobMission();
        gameNoobMission.setUserId(dto.getUserId());

        //压中: 1-阵营 2-武将 3-僵尸
        Integer type = dto.getType();
        if (type == GameNoobMissionConstant.SAN_GUO_CAMP) {
            gameNoobMission.setSanGuoCamp(1);
        } else if (type == GameNoobMissionConstant.SAN_GUO_GENERAL) {
            gameNoobMission.setSanGuoGeneral(1);
        } else if (type == GameNoobMissionConstant.ZOMBIE_FIGHT_KILL) {
            gameNoobMission.setZombieFightKill(1);
        } else {
            log.error("receiveMQ:GameNoobMissionMqDTO:type错误,type={}", type);
            return;
        }

        try {
            gameNoobMissionDao.saveOrUpdateGameNoobMission(gameNoobMission);
        } catch (Exception e) {
            log.error("save:GameNoobMission:e=", e);
        }
    }


    public GameNoobMissionDTO getStatus(Long userId) {
        GameNoobMissionDTO dto = new GameNoobMissionDTO();
        dto.setUserId(userId);
        dto.setSanGuoCamp1Num(0);
        dto.setSanGuoGeneral1Num(0);
        dto.setZombieFightKill1Num(0);
        dto.setZombieFightKill5Num(0);
        dto.setHaveBeenVipNum(0);

        GameNoobMission gn = gameNoobMissionDao.getGameNoobMissionByUserId(userId);
        if (gn == null) {
            dto.setSanGuoCamp1(NOT_SATISFIED);
            dto.setSanGuoGeneral1(NOT_SATISFIED);
            dto.setZombieFightKill1(NOT_SATISFIED);
            dto.setZombieFightKill5(NOT_SATISFIED);
        } else {
            if (gn.getSanGuoCamp() < 1) {
                dto.setSanGuoCamp1(NOT_SATISFIED);
            } else if (gn.getSanGuoCampAward()) {
                dto.setSanGuoCamp1Num(1);
                dto.setSanGuoCamp1(HAVE_GET_AWARD);
            } else {
                dto.setSanGuoCamp1Num(1);
                dto.setSanGuoCamp1(SATISFIED);
            }

            if (gn.getSanGuoGeneral() < 1) {
                dto.setSanGuoGeneral1(NOT_SATISFIED);
            } else if (gn.getSanGuoGeneralAward()) {
                dto.setSanGuoGeneral1Num(1);
                dto.setSanGuoGeneral1(HAVE_GET_AWARD);
            } else {
                dto.setSanGuoGeneral1Num(1);
                dto.setSanGuoGeneral1(SATISFIED);
            }

            if (gn.getZombieFightKill() < 1) {
                dto.setZombieFightKill1(NOT_SATISFIED);
            } else if (gn.getZombieFightKillAward1()) {
                dto.setZombieFightKill1Num(1);
                dto.setZombieFightKill1(HAVE_GET_AWARD);
            } else {
                dto.setZombieFightKill1Num(1);
                dto.setZombieFightKill1(SATISFIED);
            }

            if (gn.getZombieFightKill() < 5) {
                dto.setZombieFightKill5(NOT_SATISFIED);
                dto.setZombieFightKill5Num(gn.getZombieFightKill());
            } else if (gn.getZombieFightKillAward5()) {
                dto.setZombieFightKill5Num(5);
                dto.setZombieFightKill5(HAVE_GET_AWARD);
            } else {
                dto.setZombieFightKill5Num(5);
                dto.setZombieFightKill5(SATISFIED);
            }
        }

        //判断vip是否可以领取
        if (gn == null) {
            boolean flag = CommonUtil.null2Boolean(userInfoDao.getUserFirstVip(userId));
            if (flag) {
                dto.setHaveBeenVipNum(1);
                dto.setHaveBeenVip(SATISFIED);
            } else {
                dto.setHaveBeenVip(NOT_SATISFIED);
            }
        } else {
            if (gn.getHaveBeenVipAward()) {
                dto.setHaveBeenVipNum(1);
                dto.setHaveBeenVip(HAVE_GET_AWARD);
            } else {
                boolean flag = CommonUtil.null2Boolean(userInfoDao.getUserFirstVip(userId));
                if (flag) {
                    dto.setHaveBeenVipNum(1);
                    dto.setHaveBeenVip(SATISFIED);
                } else {
                    dto.setHaveBeenVip(NOT_SATISFIED);
                }
            }
        }

        return dto;
    }

    @Transactional(rollbackFor = Exception.class)
    public void getAward(Long userId, Integer type) {
        Lock lock = segmentedLockManager.getLock(String.valueOf(userId));
        lock.lock();
        try {
            GameNoobMissionDTO dto = getStatus(userId);
            GameNoobMission gn = new GameNoobMission();
            if (type == 1) {
                if (dto.getSanGuoCamp1() != SATISFIED) {
                    throw new ConsumeRuntimeException("无法领取");
                }
                gn.setSanGuoCampAward(true);
            } else if (type == 2) {
                if (dto.getSanGuoGeneral1() != SATISFIED) {
                    throw new ConsumeRuntimeException("无法领取");
                }
                gn.setSanGuoGeneralAward(true);
            } else if (type == 3) {
                if (dto.getZombieFightKill1() != SATISFIED) {
                    throw new ConsumeRuntimeException("无法领取");
                }
                gn.setZombieFightKillAward1(true);
            } else if (type == 4) {
                if (dto.getZombieFightKill5() != SATISFIED) {
                    throw new ConsumeRuntimeException("无法领取");
                }
                gn.setZombieFightKillAward5(true);
            } else if (type == 5) {
                //充值vip
                if (dto.getHaveBeenVip() != SATISFIED) {
                    throw new ConsumeRuntimeException("无法领取");
                }
                gn.setHaveBeenVipAward(true);
            } else {
                throw new ConsumeRuntimeException("type 错误");
            }

            gn.setUserId(userId);
            int result = gameNoobMissionDao.saveOrUpdateGameNoobMission(gn);
            CheckSqlResultUtil.checkResult(result);

            //为用户加寻豆
            BillDetailBeans billDetailBeans = new BillDetailBeans();
            long beans;
            if (type < 5) {
                beans = 1000L;
            } else if (type == 5) {
                beans = 10000L;
            } else {
                throw new ConsumeRuntimeException("type 错误");
            }

            //统计
            LocalDate now = LocalDate.now();
            gameDataService.increaseNoobMissionNum(now, userId);
            gameDataService.increaseNoobMissionExpend(now, beans);

            //钱包与明细
            UserWallet uw = new UserWallet();
            uw.setBeans(beans);
            uw.setUserId(userId);
            result = userWalletDao.plusUserWalletBeans(uw);
            CheckSqlResultUtil.checkResult(result);

            billDetailBeans.setBeans(beans);
            billDetailBeans.setBeansType(BeansType.GAME_NOOB_MISSION.getCode());
            billDetailBeans.setUserId(userId);
            billDetailBeans.setRatio(0);
            result = billDetailBeansDao.saveBillDetailBeans(billDetailBeans);
            CheckSqlResultUtil.checkResult(result);

        } catch (ConsumeRuntimeException e) {
            throw e;
        } catch (Exception e) {
            log.error("GameNoobMission:getAward:e=", e);
            throw new ConsumeRuntimeException("领取失败");
        } finally {
            lock.unlock();
        }

    }


}
